var dbCongif = require("../utils/dbconfig");

// 随机验证码
function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// 声明验证码和手机号数组
ValidatePhoneCode = [];
// 判断该手机是否一定接收过该验证码
let sendCodeP = (phone) => {
  for (var item of ValidatePhoneCode) {
    console.log("item", item);
    if (phone == item.phone) {
      return true;
    }
  }
  return false;
};

//
let findCodeAndPhone = (phone, code) => {
  for (var item of ValidatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return "login";
    }
  }
  return "error";
};

// 验证码发送接口
sendCode = (req, res) => {
  // 判断该手机号是否一定接收过验证码
  let phone = req.query.phone;
  if (sendCodeP(phone)) {
    res.send({
      code: 400,
      msg: "已经发送过验证码，稍后再发",
    });
  }

  let codeMge = rand(1000, 9999);
  ValidatePhoneCode.push({
    phone: phone,
    code: codeMge,
  });
  res.send({
    code: 200,
    msg: "发送成功",
  });
  console.log("code", codeMge);
};

// 验证码登录
codePhoneLogin = (req, res) => {
  let { phone, code } = req.query;

  // 判断手机号是否发送过验证码
  if (sendCodeP(phone)) {
    // 验证码和手机号是否匹配
    let state = findCodeAndPhone(phone, code);
    if (state == "login") {
      // 登录成功
      res.send({
        code: "200",
        mgs: "登录成功",
      });
    } else if (state == "error") {
      res.send({
        code: "500",
        mgs: "登录失败",
      });
    }
  } else {
    res.send({
      code: "400",
      mgs: "未发送验证码",
    });
  }
};

module.exports = {
  sendCode,
  codePhoneLogin,
};
